﻿namespace FlashPay.Admin.Controllers
{
    using AutoMapper;
    using Demo.Entity.Config;

    using Microsoft.Extensions.Options;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Mvc;
    using FlashPay.Entity;
    using System;
    using System.IO;

    public class UploadController : Controller
    {
        private IHostingEnvironment _hostingEnv;

        /// <summary>
        /// 上传配置
        /// </summary>
        private readonly UploadConfig _uploadConfig;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="env"></param>
        /// <param name="option">上传配置</param>
        public UploadController(IHostingEnvironment env, IOptions<UploadConfig> option)
        {
            this._hostingEnv = env;
            this._uploadConfig = option.Value;
        }

        public JsonResult Index()
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {

                if (Request.Form.Files.Count == 0)
                {
                    throw new Exception("未检测到文件");
                }

                var files = Request.Form.Files;

                //格式限制
                var allowType = new string[] { "image/jpg", "image/png" };

                foreach (var file in files)
                {
                    //扩展名
                    var extensionName = Path.GetExtension(file.FileName);
                    // 原文件名（包括路径）
                    var fileName = Path.Combine("uploadfiles", Guid.NewGuid().ToString("N") + extensionName);
                    //创建文件夹
                    if (!Directory.Exists(_hostingEnv.WebRootPath + @"\uploadfiles"))
                        Directory.CreateDirectory(_hostingEnv.WebRootPath + @"\uploadfiles");
                    //物理路径
                    string savePath = Path.Combine(_hostingEnv.WebRootPath, fileName);
                    //保存文件
                    using (FileStream fs = new FileStream(savePath, FileMode.CreateNew))
                    {
                        file.CopyTo(fs);
                        fs.Flush();
                    }
                }
            }
            catch (Exception ex)
            {
                response.ErrorMessage = ex.Message;
            }

            return Json(response);
        }
    }
}